<template>
  <div class="container">
    <!-- 顶部操作按钮 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd" class="add-button">
        <el-icon>
          <Plus />
        </el-icon>新增
      </el-button>
    </div>

    <!-- 表格 -->
    <el-card class="table-card" shadow="hover">
      <el-table :data="tableData" border style="width: 100%" :header-cell-style="{ background: '#f5f7fa' }" stripe
        highlight-current-row>
        <el-table-column prop="province" label="省份" min-width="120" />
        <el-table-column prop="type" label="类型" min-width="120">
          <template #default="{ row }">
            <el-tag style="margin-right: 2px;" v-if="row.type.includes('1')">招考信息</el-tag>
            <el-tag v-if="row.type.includes('2')">视频课程</el-tag>
            <span v-else>未知类型</span>
          </template>
        </el-table-column>

        <el-table-column prop="imageUrl" label="图片" min-width="300">
          <template #default="{ row }">
            <div v-if="row.imageUrl && row.imageUrl.length" class="image-preview">
              <!-- :preview-src-list="row.imageUrl" -->
              <el-image v-for="(img, index) in row.imageUrl" :key="index" :src="img" class="preview-image" fit="cover">
              </el-image>
            </div>
            <el-empty v-else description="无图片" :image-size="60" />
          </template>
        </el-table-column>
        <!-- updateTime -->
        <el-table-column prop="updateTime" label="更新时间" min-width="120">
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" size="small" @click="handleEdit(row)" :icon="Edit">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)" :icon="Delete">删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="800px" :close-on-click-modal="false" destroy-on-close
      class="custom-dialog">
      <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" class="dialog-form">
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" style="width: 200px;" multiple>
            <el-option label="招考信息" value="1" />
            <el-option label="视频课程" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <div class="province-selection">
            <el-button size="small" @click="handleSelectAllProvinces" type="primary">
              {{ form.province.length === provinces.length ? '取消全选' : '全选' }}
            </el-button>
            <el-checkbox-group v-model="form.province" @change="handleProvinceChange" class="province-checkbox-group">
              <div class="province-grid">
                <el-checkbox v-for="item in provinces" :key="item.value" :label="item.value" class="province-item"
                  border>
                  {{ item.label }}
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </el-form-item>
        <el-form-item label="图片" prop="imageUrl">
          <custom-upload v-model="form.imageUrl" type="expand" :limit="3" :action="serverDefaultCfg.ossURL" :data="{}"
            :headers="{}" :multiple="true" class="custom-upload" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" :icon="Close">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :icon="Check">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Edit, Delete, Close, Check, Picture } from '@element-plus/icons-vue';
import cityData from '@/api/zhaokao/citydata';
import customUpload from '@/components/CustomUpload/index.vue';
import { serverDefaultCfg } from '@/common/http/config';
import {
  addProvinceImage, getProvinceImages, deleteProvinceImage
} from '@/api/zhaokao/zhaokao';
const provinces = computed(() => {
  const arr = cityData
    .map(item => ({
      value: item.value,
      label: item.label,
    }))
    .sort((a, b) => a.label.localeCompare(b.label, 'zh-CN'));
  return arr;
});
// 表格数据
const tableData = ref([
]);

// 表单数据
const form = ref({
  province: [], // 改为数组以支持多选
  imageUrl: [],
  type: '1'
});

// 表单验证规则
const rules = {
  province: [{ required: false, message: '请选择省份', trigger: 'change', type: 'array' }],
  imageUrl: [{ required: true, message: '请上传图片', trigger: 'change' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
};

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('新增');
const formRef = ref(null);
const getList = () => {
  getProvinceImages().then((res) => {
    console.log(res);
    tableData.value = res.data;
  })
}
getList();


// 新增按钮处理
const handleAdd = () => {
  dialogTitle.value = '新增';
  form.value = {
    province: [], // 初始化为空数组
    imageUrl: [],
    type: '1'
  };
  dialogVisible.value = true;
};

// 编辑按钮处理
const handleEdit = (row) => {
  dialogTitle.value = '编辑';
  row.type=row.type.split(',');

  form.value = {
    ...row,
    province: row.province ? row.province.split(',') : [], // 将逗号分隔的字符串转换为数组
    imageUrl: row.imageUrl ? row.imageUrl.map(url => ({
      url: url,
      downloadUri: url, // 保持原有的下载链接
      name: new Date().getTime() + '.jpg' // 生成一个唯一的文件名
    })) : [] // 转换为上传组件需要的格式
  };
  console.log(form.value);

  dialogVisible.value = true;
};

// 删除按钮处理
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteProvinceImage(row.id).then((res) => {
      if (res.code == 200) {
        ElMessage.success('删除成功');
        getList();
      } else {
        ElMessage.error('删除失败');
      }
    })
  }).catch(() => { });
};

// 表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate((valid) => {
    if (valid) {
      if (!form.value.id) {
        console.log(form.value);
        const obj = {
          province: form.value.province.join(','), // 将数组转换为逗号分隔的字符串
          imageUrl: form.value.imageUrl.map(item => item.downloadUri), // 将数组转换为逗号
          type: form.value.type.join(','),
        }
        // return
        addProvinceImage(obj).then((res) => {
          console.log(res);
          if (res.code == 200) {
            ElMessage.success('新增成功');
            dialogVisible.value = false;
            getList();
          }
        }).catch(() => {
          ElMessage.error('新增失败');
        });

      } else {
        const obj = {
          id: form.value.id,
          province: form.value.province.join(','), // 将数组转换为逗号分隔的字符串
          imageUrl: form.value.imageUrl.map(item => item.downloadUri), // 将数组转换为逗号
          type: form.value.type.join(','),
        }
        addProvinceImage(obj).then((res) => {
          console.log(res);
          if (res.code == 200) {
            ElMessage.success('编辑成功');
            dialogVisible.value = false;
            getList();
          }
        }).catch(() => {
          ElMessage.error('编辑失败');
        });
      }



    }
  });
};

// 处理全选按钮点击
const handleSelectAllProvinces = () => {
  if (form.value.province.length === provinces.value.length) {
    // 如果已经全选，则取消全选
    form.value.province = [];
  } else {
    // 如果未全选，则全选
    form.value.province = provinces.value.map(item => item.value);
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 10px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  // justify-content: flex-end;
}

.add-button {
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
  }
}

.table-card {
  border-radius: 8px;
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding: 20px;
  }
}

.image-preview {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.preview-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  transition: all 0.3s;

  // &:hover {
  //   transform: scale(1.05);
  //   box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  // }
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

.province-selection {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;

  .el-button {
    margin-bottom: 10px;
  }
}

.province-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 10px;
  margin: 10px 0;
}

.province-item {
  margin-right: 0 !important;
}

.dialog-form {
  padding: 20px;
}

.custom-dialog {
  :deep(.el-dialog__header) {
    margin-right: 0;
    padding: 20px;
    border-bottom: 1px solid #dcdfe6;
  }

  :deep(.el-dialog__body) {
    padding: 0;
  }

  :deep(.el-dialog__footer) {
    padding: 20px;
    border-top: 1px solid #dcdfe6;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.custom-upload {
  width: 100%;
}
</style>
